package org.example.controller;

import org.apache.ibatis.session.SqlSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.example.domain.Teacher;
import org.example.mapper.TeacherMapper;
import org.example.realm.TeacherRealm;
import org.example.util.MyBatisUtil;

import java.util.Scanner;
import java.util.UUID;

/**
 * @author 李新雨的项目86176
 * @version 1.0
 * @date 2024-12-15 19:09
 */
public class TeacherController {

    public static void main(String[] args) {
        TeacherController.login();
    }

    public static void register(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入教师姓名：");
        String name=scanner.nextLine();
        System.out.println("请输入教师密码：");//15984
        String password=scanner.nextLine();

        System.out.println("请输入教师地址：");
        String address=scanner.nextLine();
        System.out.println("请输入教师角色：");
        String role=scanner.nextLine();
        UUID uuid=UUID.randomUUID();
        String salt = uuid.toString().substring(0, 5);
        System.out.println("盐值："+salt);
        Md5Hash md5Hash=new Md5Hash(password,salt,3);
        String md5Password=md5Hash.toString();
        SqlSession session = MyBatisUtil.getSession();
        TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class);
        Teacher teacher=new Teacher(null,name,md5Password,address,role,salt);
        teacherMapper.insert(teacher);
        session.commit();


    }

    public static void login(){
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        TeacherRealm  teacherRealm=new TeacherRealm();
        defaultSecurityManager.setRealm(teacherRealm);

        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("md5");
        hashedCredentialsMatcher.setHashIterations(3);
        teacherRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入教师姓名：");
        String name=scanner.nextLine();
        System.out.println("请输入教师密码：");
        String password=scanner.nextLine();
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        subject.login(token);
        if (subject.isAuthenticated()){
            System.out.println("登录成功");
        }
        boolean permitted = subject.isPermitted("teacher:select");
        System.out.println(permitted);

    }
}
